<template>
    <div>
        <use-page-header/>
        <div class="wrapper">
            <a-card>
                <a-flex class="margin-bottom" justify="space-between">
                    <a-button type="primary" @click="showModal"><PlusOutlined/>添加分类</a-button>
                    <div>
                        <a-input-search placeholder="输入关键字搜索" name="keywords" @search="filterData" allow-clear/>
                    </div>
                </a-flex>
                <a-table :columns="columns" 
                :rowSelection="{}" :loading="state.loading" 
                rowKey="id"
                :pagination="tablePagination"
                :data-source="data">
                    <template #bodyCell="{column,record}">
                        <template v-if="column.dataIndex === 'action'">
                            <div class="actions">
                                <span @click="showModal(record)">编辑</span>
                                <span @click="showModal(undefined,record.id)">添加子分类</span>
                                <span @click="onDelete(record.id)">删除</span>
                            </div>
                        </template>
                    </template>
                </a-table>
            </a-card>
        </div>
        <CategoryModal v-model:open="state.open" :pid="state.pid" :data-item="dataItem" @ok="getData"/>
    </div>
</template>

<script lang="ts" setup>
import {UsePageHeader} from '@/components'
import {PlusOutlined} from '@ant-design/icons-vue'
import {ref,onMounted, reactive} from 'vue'
import {deleteCategory, getCategoryList} from '@/server/modules/category'
import CategoryModal from './components/CategoryModal.vue'
import { tablePagination } from '@/config'
import useMessage from '@/hooks/useMessage'
import { Modal } from 'ant-design-vue'
import { hasPermission } from '@/hooks'

const data = ref<Category[]>([])
const dataItem = ref<Category>()
const dataSource = ref<Category[]>([])

const state = reactive({
    open:false,
    loading:false,
    pid:0
})
const showModal = (item?:Category,pid?:number)=>{ 
    state.open = true
    dataItem.value = item
    if(pid) state.pid = pid
}
const columns = [
    {title:'分类名称',dataIndex:'name'},
    {title:'操作',dataIndex:'action',width:200}
]
const filterData = (keywords:string)=>{ 
    if(!keywords) return data.value = dataSource.value
     const filterTree = (nodes: any[]) => {
        return nodes.reduce((acc, node) => {
            const matchesCurrent = node.name.includes(keywords);
            const matchesChildren = node.children && node.children.length > 0 
                ? filterTree(node.children).length > 0 
                : false;

            if (matchesCurrent || matchesChildren) {
                acc.push({
                    ...node,
                    children: matchesChildren ? filterTree(node.children) : []
                });
            }

            return acc;
        }, [] as any[]);
    };

    data.value = filterTree(dataSource.value);
}
const getData = async ()=>{
    try{
        state.loading = true
        const res = await getCategoryList()
        data.value = res
        state.loading = false
        dataSource.value = res
    }catch(err){
        console.log(err);
    }finally{
        setTimeout(() => {
            state.loading = false
        }, 500);
    }
}
const onDelete = (id:number)=>{ 
    if(!hasPermission('delete')) return
    Modal.confirm({
        title:'提示',
        content:'确定要删除吗？',
        onOk:async()=>{
            const res = await deleteCategory(id)
            if(res.code === 200){
                useMessage(res.code,res.message)
                getData()
            }else{
                useMessage(res.code,res.message)
            }
        }
    })
}
onMounted(()=>{getData()})
</script>

<style scoped>

</style>